﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Atmk.WaterMeter.MIS.Commons.ViewModels.District;
using Atmk.WaterMeter.MIS.TestForm.Common;
using Atmk.WaterMeter.MIS.TestForm.Common.Utils;
using Common.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NKnife.IoC;
using RestSharp;
using SimpleJson;
using WeifenLuo.WinFormsUI.Docking;

namespace Atmk.WaterMeter.MIS.TestForm.Views.XiangZhanAo
{
    public partial class CT_NB_IoTPlatformView : DockContent
    {
        private static readonly ILog _Logger = LogManager.GetLogger<CT_NB_IoTPlatformView>();
        private readonly Dictionary<string, Device> _DeviceManage;
        private readonly Kernel _kernel;

        public CT_NB_IoTPlatformView()
        {
            _kernel = DI.Get<Kernel>();
            InitializeComponent();
            _DeviceManage = new Dictionary<string, Device>();
            BindClick();
        }

        private void BindClick()
        {
            _AddDevice.Click += (s, e) => { AddDevice(); };
            _DelDevice.Click += (s, e) => { DelDevice(); };
            _ReadMetersBtn.Click += (s, e) => { ReadMeter(); };
            _ValveOpenBtn.Click += (s, e) => { ValveControl(1); };
            _ValveCloseBtn.Click += (s, e) => { ValveControl(0); };
            _DevicesBtn.Click += (s, e) => { SelectDevices(); };
            _listBox.SelectedIndexChanged += (s, e) => { SelctChange(); };
        }

        private void SelectDevices()
        {
            try
            {
                var resoure = UrlManager.CT_Device + "s";
                var request = new RestRequest(resoure, Method.GET);
                request.AddHeader("X-Token", _kernel.Token);
                _kernel.Client.ExecuteAsync(request, response =>
                {
                    var data = response.Content;
                    try
                    {
                        _Logger.Debug(data);
                        var result = JsonConvert.DeserializeObject<JObject>(data);
                        if (result["errcode"].ToString() == "0")
                        {
                            var resdata = JsonConvert.DeserializeObject<JObject>(result["data"].ToString());
                            SetPropertyGrid(result);
                            var jarray = JsonConvert.DeserializeObject<JArray>(resdata["devices"].ToString());
                            var jobjs = jarray.Select(j =>JsonConvert.DeserializeObject<JObject>(j.ToString())).ToList();
                            //赋值
                            _DeviceManage.Clear();
                            jobjs.ForEach(j =>
                            {
                                _DeviceManage[j["name"].ToString()] = new Device
                                {
                                    DeviceId = j["deviceId"].ToString(),
                                    Imei = j["imei"].ToString(),
                                    Number = j["name"].ToString()
                                };
                            });
                            BindList();
                            _Logger.Info($"平台设备读取成功");
                        }
                        else
                        {
                            _Logger.Error($"APIError:{result["msg"]}");
                        }
                    }
                    catch (Exception exception)
                    {
                        _Logger.Error(exception);
                    }
                });
            }
            catch (Exception e)
            {
                _Logger.Error(e);
            }
        }

        private void ValveControl(int valveState)
        {
            if (_DeviceId.Text == "")
            {
                _Logger.Warn("没有选中设备id");
                return;
            }
            try
            {
                var resoure = UrlManager.CT_Valve;
                var request = new RestRequest(resoure, Method.POST);
                var number = _MeterNoText.Text;
                var deviceId = _DeviceId.Text;
                var state = valveState == 1 ? "开阀" : "关阀";
                request.AddHeader("X-Token", _kernel.Token);
                request.AddJsonBody(new {deviceId, valve = valveState});
                _kernel.Client.ExecuteAsync(request, response =>
                {
                    var data = response.Content;
                    try
                    {
                        _Logger.Debug(data);
                        var result = JsonConvert.DeserializeObject<JObject>(data);
                        if (result["errcode"].ToString() == "0")
                        {
                            _Logger.Info($"水表{number}{state}指令下发成功");
                        }
                        else
                        {
                            _Logger.Error($"APIError:{result["msg"]}");
                        }
                    }
                    catch (Exception exception)
                    {
                        _Logger.Error(exception);
                    }
                });
            }
            catch (Exception e)
            {
                _Logger.Error(e);
            }
        }

        private void ReadMeter()
        {
            if (_DeviceId.Text == "")
            {
                _Logger.Warn("没有选中设备id");
                return;
            }
            try
            {
                var resoure = UrlManager.CT_DevInfo + $"/{_DeviceId.Text}";
                var request = new RestRequest(resoure, Method.GET);
                var number = _MeterNoText.Text;
                request.AddHeader("X-Token", _kernel.Token);
                _kernel.Client.ExecuteAsync(request, response =>
                {
                    var data = response.Content;
                    try
                    {
                        _Logger.Debug(data);
                        var result = JsonConvert.DeserializeObject<JObject>(data);
                        if (result["errcode"].ToString() == "0")
                        {
                            var resdata = JsonConvert.DeserializeObject<JObject>(result["data"].ToString());
                            SetPropertyGrid(resdata);
                            _Logger.Info($"水表{number}读取数据成功");
                        }
                        else
                        {
                            _Logger.Error($"APIError:{result["msg"]}");
                        }
                    }
                    catch (Exception exception)
                    {
                        _Logger.Error(exception);
                    }
                });
            }
            catch (Exception e)
            {
                _Logger.Error(e);
            }
        }

        private void SelctChange()
        {
            var number = _listBox.SelectedItem.ToString();
            if (!_DeviceManage.ContainsKey(number)) return;
            var device = _DeviceManage[number];
            _MeterNoText.Text = device.Number;
            _IMEI.Text = device.Imei;
            _DeviceId.Text = device.DeviceId;
        }

        private void DelDevice()
        {
            try
            {
                var resoure = UrlManager.CT_Device + $"/{_DeviceId.Text}";
                var request = new RestRequest(resoure, Method.DELETE);
                var imei = _IMEI.Text;
                var number = _MeterNoText.Text;
                request.AddHeader("X-Token", _kernel.Token);
                request.AddJsonBody(new {imei, model = "WaterMeter", number});
                _kernel.Client.ExecuteAsync(request, response =>
                {
                    var data = response.Content;
                    try
                    {
                        _Logger.Debug(data);
                        var result = JsonConvert.DeserializeObject<JsonObject>(data);
                        if (result["errcode"].ToString() == "0")
                        {
                            _DeviceManage.Remove(number);
                            BindList();
                        }
                        else
                        {
                            _Logger.Error($"APIError:{result["msg"]}");
                        }
                    }
                    catch (Exception exception)
                    {
                        _Logger.Error(exception);
                    }
                });
            }
            catch (Exception e)
            {
                _Logger.Error(e);
            }
        }

        private void AddDevice()
        {
            try
            {
                var resoure = UrlManager.CT_Device;
                var request = new RestRequest(resoure, Method.POST);
                var imei = _IMEI.Text;
                var number = _MeterNoText.Text;
                request.AddHeader("X-Token", _kernel.Token);
                request.AddJsonBody(new {imei, model = "WaterMeter", number});
                _kernel.Client.ExecuteAsync(request, response =>
                {
                    var data = response.Content;
                    try
                    {
                        _Logger.Debug($"data:{data}");
                        if (data == "")
                        {
                            _Logger.Error("没有获取数据");
                        }
                        else
                        {
                            var result = JsonConvert.DeserializeObject<JsonObject>(data);
                            if (result["errcode"].ToString() == "0")
                            {
                                var resdata = JsonConvert.DeserializeObject<JsonObject>(result["data"].ToString());
                                _DeviceManage[number] = new Device
                                {
                                    DeviceId = resdata["deviceId"].ToString(),
                                    Imei = imei,
                                    Number = number
                                };
                                BindList(number);
                            }
                            else
                            {
                                _Logger.Error($"APIError:{result["msg"]}");
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        _Logger.Error(exception);
                    }
                });
            }
            catch (Exception e)
            {
                _Logger.Error(e);
            }
        }

        private void BindList(string number="")
        {
            Invoke((EventHandler) delegate
            {
                _listBox.Items.Clear();
                _DeviceManage.AsEnumerable().ForEach(k => { _listBox.Items.Add(k.Value.Number); });
                if (number != "")
                    _listBox.SelectedItem = number;
                else
                {
                    _listBox.SelectedIndex = 0;
                }
            });
        }

        private void SetPropertyGrid(JObject obj)
        {
            Invoke((EventHandler)delegate
            { 
                _PropertyGrid.SelectedObject = new JTypeDescriptor(obj);
            });
        }
    }

    public class Device
    {
        public string Number { get; set; }
        public string Imei { get; set; }
        public string DeviceId { get; set; }
    }
}